<extend name="public/base2" />
<block name="head">
    <!-- ElementUI 最新版 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</block>
<block name="main-content">
    <el-card class="box-card" id="create">
        <!-- card-header -->
        <div slot="header" class="clearfix">
            <span>新增 - ElementUI</span>
        </div>
        <!-- card-body -->
        <el-alert
            v-for="(msg, key) in alertMessage" 
            :key="key" 
            :title="msg" 
            type="error" 
            show-icon
        ></el-alert>
        <el-form 
            ref="form" 
            :model="form" 
            label-width="90px" 
            label-position="right" 
            :rules="rules"
            status-icon
        >
            <el-row :gutter="15">
                <el-col :span="16" :lg="12" :xl="10">
                    <el-form-item label="角色组" prop="role" >
                        <el-select id="role" v-model="form.role" placeholder="请选择">
                            <el-option 
                                v-for="item in roleOptions"
                                :key="item.id"
                                :label="item.title"
                                :value="item.id"
                                :disabled="!Boolean(item.status)"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :lg="9" :xl="9"></el-col>
            </el-row>
            <el-row :gutter="15">
                <el-col :span="16" :lg="12" :xl="10">
                    <el-form-item label="用户名" prop="username">
                        <el-input 
                            id="username"
                            v-model="form.username"
                            label="用户名"
                            maxlength="20"
                            minlength="4" 
                            placeholder="请输入用户名"
                            suffix-icon="el-icon-user"
                            clearable
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :lg="9" :xl="9">
                    <small class="text-danger">用户名长度在4到20个字符之间，且用户名只能是字母、数字、下划线或它们的组合</small>
                </el-col>
            </el-row>
            <el-row :gutter="15">
                <el-col :span="16" :lg="12" :xl="10">
                    <el-form-item label="密码" prop="password">
                        <el-input 
                            id="password"
                            v-model="form.password"
                            label="密码"
                            maxlength="100"
                            minlength="6" 
                            placeholder="请输入密码"
                            suffix-icon="el-icon-lock"
                            show-password
                            clearable
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :lg="9" :xl="9">
                    <small class="text-danger">密码应当不少于6个字符，且至少包含字母和数字</small>
                </el-col>
            </el-row>
            <el-row :gutter="15">
                <el-col :span="16" :lg="12" :xl="10">
                    <el-form-item label="确认密码" prop="confirmPassword">
                        <el-input 
                            id="confirmPassword"
                            v-model="form.confirmPassword"
                            label="确认密码"
                            maxlength="100"
                            minlength="6" 
                            placeholder="请再次输入密码"
                            suffix-icon="el-icon-lock"
                            show-password
                            clearable
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :lg="9" :xl="9"></el-col>
            </el-row>
            <el-row :gutter="15">
                <el-col :span="16" :lg="12" :xl="10">
                    <el-form-item label="头像" prop="avatar">
                        <el-autocomplete
                            popper-class="avatar"
                            v-model="form.avatar"
                            label="头像"
                            :fetch-suggestions="querySearch"
                            value-key="path"
                            placeholder="请选择头像"
                            suffix-icon="el-icon-picture-outline-round"
                            clearable
                        >
                            <template v-slot="{item}">
                                <div class="pic d-inline-block">
                                    <el-avatar :src="item.path" @error="true">
                                        <el-avatar icon="el-icon-picture-outline-round"></el-avatar>
                                    </el-avatar>
                                </div>
                                <div class="name d-inline-block align-top ml-2">{{item.name}}</div>
                            </template>
                            <el-upload
                                class="upload-demo"
                                slot="append" 
                                ref="upload"
                                name="avatar_file"
                                action="#"
                                :on-change="handleChange"
                                :auto-upload="false"
                                :show-file-list="false"
                            >
                                <el-button slot="trigger" type="primary" class="folder-opened" icon="el-icon-folder-opened"></el-button>
                            </el-upload>
                        </el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :lg="9" :xl="9"></el-col>
            </el-row>
            <el-row :gutter="15">
                <el-col :span="16" :lg="12" :xl="10">
                    <el-form-item label="邮箱地址" prop="email">
                        <el-input 
                            id="email"
                            v-model="form.email"
                            label="邮箱地址"
                            placeholder="请输入邮箱地址"
                            suffix-icon="el-icon-message"
                            clearable
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :lg="9" :xl="9">
                    <small class="text-info">
                        {$Think.session.admin.group_id === 1 ? '改进：输入时下拉显示一些常用邮箱后缀' : ''}
                    </small>
                </el-col>
            </el-row>
            <el-row :gutter="15">
                <el-col :span="16" :lg="12" :xl="10">
                    <el-form-item label="昵称" prop="nickname">
                        <el-input 
                            id="nickname"
                            v-model="form.nickname"
                            label="昵称"
                            maxlength="20"
                            minlength="2" 
                            placeholder="请输入昵称"
                            suffix-icon="far fa-smile-wink"
                            clearable
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :lg="9" :xl="9">
                    <small class="text-danger">昵称长度在2到20个字符之间，且昵称只能是字母、数字、下划线_、破折号-及汉字</small>
                </el-col>
            </el-row>
            <el-row :gutter="15">
                <el-col :span="16" :lg="12" :xl="10">
                    <el-form-item label="状态" prop="status">
                        <el-radio-group v-model="form.status" size="medium">
                            <el-radio-button label="1">显示</el-radio-button>
                            <el-radio-button label="0">隐藏</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :lg="9" :xl="9"></el-col>
            </el-row>
            <el-row :gutter="15">
                <el-col :span="16" :lg="12" :xl="10">
                    <el-form-item>
                        <el-button type="primary" :loading="loading" @click="onSubmit">提交</el-button>
                        <el-button type="primary" @click="resetForm('form')">重置</el-button>
                        <el-button type="primary" @click="goBack">返回</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="8" :lg="9" :xl="9"></el-col>
            </el-row>
        </el-form>
    </el-card>
</block>
<block name="footer-script">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script>window.jQuery || document.write('<script src="__ADMINLTE__/plugins/jquery/jquery.min.js"><\/script>')</script>
    <!-- AdminLTE App -->
    <script src="__ADMINLTE__/dist/js/adminlte.min.js"></script>
    <!-- Bootstrap V4 -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    <!-- Vue 开发环境版本，包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- ElementUI 最新版 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- axios(类似Ajax) -->
    <js href="https://unpkg.com/axios@latest/dist/axios.min.js" />
    <!-- Vue-Axios 最新版 -->
    <script src="https://unpkg.com/vue-axios@latest/dist/vue-axios.min.js"></script>
    <!-- App JS -->
    <script src="__STATIC__/js/app.js"></script>

    <script>
        // Vue.use(VueAxios, axios)
        new Vue({
            el: '#create',
            data() {
                let confirmValidateA = (rule, value, callback) => {
                    if ('' !== this.form.confirmPassword)
                        this.$refs.form.validateField('confirmPassword');
                    callback();
                };
                let confirmValidateB = (rule, value, callback) => {
                    if (this.form.confirmPassword !== this.form.password)
                        callback( new Error('两次输入密码不一致') );
                    callback();
                };
                let avatarValidator = (rule, value, callback) => {
                    let avatar = this.$refs.upload.$data.uploadFiles;
                    let avatarLast = avatar.length - 1;
                    if (avatar.length)
                    {
                        let imgType = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif', 'image/bmp', 'image/webp'];
                        let imgString = imgType.toString().toLowerCase();
                        let rawType = avatar[avatarLast].raw.type;
                        let error = false;
                        switch (true) {
                            case ('' === value):
                                // 清空头像图片名时，就表示不需要头像，无需错误提示
                                // callback( new Error('图片名不能为空') );
                                error = true;
                                break;
                            case (-1 === rawType.indexOf('image')):
                                callback( new Error('头像只能是图片类型') );
                                error = true;
                                break;
                            case (-1 === imgString.indexOf(rawType)):
                                callback( new Error('图片格式错误') );
                                error = true;
                                break;
                            case (avatar[avatarLast].size / 1024 / 1024 / 2 > 1):
                                callback( new Error('图片大小不能超过2M') );
                                error = true;
                                break;
                        }
                        
                        // 清空真实文件
                        true === error && (this.$refs.upload.$data.uploadFiles = []);
                    }
                    callback();
                };
                return {
                    form: {
                        role: '',
                        username: '',
                        password: '',
                        avatar: '',
                        confirmPassword: '',
                        email: '',
                        nickname: '',
                        status: '1'
                    },
                    roleOptions: JSON.parse('{$role_options}'),
                    avatarList: JSON.parse('{$avatar_list}'),
                    loading: false,
                    alertMessage: [],
                    rules: {
                        role: [
                            {required: true, message: "请选择一个角色"}
                        ],
                        username: [
                            {required: true, message: "用户名不能为空"},
                            {min: 4, max: 20, message: "用户名长度需要4到20个字符"},
                            {pattern: /^\w+$/, message: "用户名只能是字母、数字和下划线_"}
                        ],
                        password: [
                            {required: true, message: "密码不能为空"},
                            {min: 6, message: "密码长度至少6个字符"},
                            {
                                pattern: /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z~!@#$%^&*()><,.?\-_=+/|;:'"]{6,100}$/, 
                                message: "密码必须包含字母和数字"
                            },
                            {validator: confirmValidateA}
                        ],
                        confirmPassword: [
                            {required: true, message: "确认密码不能为空"},
                            {validator: confirmValidateB}
                        ],
                        avatar: [
                            {validator: avatarValidator, trigger: 'change'}
                        ],
                        email: [
                            {required: true, message: "邮箱地址不能为空"},
                            {type: 'email', message: "不是有效的邮箱地址"}
                        ],
                        nickname: [
                            {min: 2, max: 20, message: "昵称长度需要2到20个字符"},
                            {pattern: /^[\u4e00-\u9fa5\w\-]*$/, message: "昵称只能是字母、数字、下划线_、破折号-及汉字"}
                        ],
                        status: [
                            {required: true, message: "状态不能为空"},
                            {type: 'enum', enum: ['0', '1'], message: "状态值无效"}
                        ]
                    }
                }
            },
            methods: {
                querySearch(queryString, cb) {
                    let avatarResults = this.avatarList;
                    let results = queryString ? avatarResults.filter(this.createFilter(queryString)) : avatarResults;
                    
                    cb(results);
                },
                createFilter(queryString) {
                    return (avatarResult) => {
                        return avatarResult.path.toLowerCase().indexOf(queryString.toLowerCase()) !== -1;
                    };
                },
                handleChange(file) {
                    if (file.status == "ready")
                        this.form.avatar = file.name;
                    console.log(file);
                },
                resetForm(formName) {
                    this.$refs.upload.$data.uploadFiles = [];
                    this.$refs[formName].resetFields();
                    this.alertMessage = '';
                    this.loading = false;
                },
                onSubmit() {
                    this.$refs.form.validate((valid) => {
                        if (valid)
                        {
                            this.loading = true;
                            var formObj = new FormData();
                            formObj.append('form', JSON.stringify(this.form));
                            if (this.$refs.upload.$data.uploadFiles.length)
                                formObj.append('avatarFile', this.$refs.upload.$data.uploadFiles[0].raw);
                            formObj.append('__token__', '{$Request.token}');
                            let vm = this;
                            this.axios.post('{:url("admins/")}?_ajax=1', formObj)
                            .then(function(response) {
                                if (1 === response.data.code)
                                {
                                    if (response.url)
                                        window.location.href = response.data.url;
                                    
                                    // 新建成功返回管理员列表页
                                    history.back(-1);
                                } else if (0 === response.data.code) {
                                    vm.alertMessage = response.data.data;
                                }
                            })
                            .catch(function(error) {
                                vm.alertMessage.push(adminEditingError(error));
                            })
                        } else {
                            return false;
                        }
                    });
                }
            }
        })
    </script>
</block>